import { _decorator, Component, director, Label, Node } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('Guessing')
export class Guessing extends Component {
    @property({type: Node}) 
    private enemySkillNodes: Node = null; // 敌人技能节点
    @property({type: Label})
    private hintLabel: Label = null; // 绑定hint 节点


    private enemyAttackType = 0 ; // 敌人招式 【0-弓箭 1-流星锤 2-盾牌】【克制关系0>1>2>0】
    private timer = null; // 计时器
    start() {
        this.timer = setInterval(()=>{
            this.randEnemyAttack();
        }, 200)
    }

    update(deltaTime: number) {
        
    }
// 敌人随机招式
    randEnemyAttack(){
        this.enemyAttackType = Math.floor(Math.random() * 3); // 敌人随机招式类型
        let childSkillNodes = this.enemySkillNodes.children; // 获取子节点
        for(let item of childSkillNodes){
            item.name === this.enemyAttackType.toString()? item.active = true:  item.active = false
        }
    }

    // 判决结果
    judgeOutcome(playerAttack: string, enemyAttack: string): string{
        try{
            // 定义克制关系 
            const techniqueRelations = {
                '0': {'0': 'dogfall','1': 'win', '2': 'lose'},// 弓箭：克流星锤，被盾牌克  
                '1': {'0': 'lose','1': 'dogfall', '2': 'win'}, // 流星锤：被弓箭克，克盾牌  
                '2': {'0': 'win','1': 'lose', '2': 'dogfall'}, // 盾牌：克弓箭，被流星锤克  
            }
            const results = techniqueRelations[playerAttack][enemyAttack]
            return results // win or lose or dogfall
        }
        catch(err){
            console.warn(err)
        }
     
    }

 
    // 玩家出招
    attack(event: any, customEventData: any){
        if(!this.timer) return;
        // 玩家出招时，清除定时器
        clearInterval(this.timer);
        this.timer = null;

       

        let attackType = event.target.name; // 获取目标节点的name, name是enemySkillNodes的子节点 0,1,2
        let attackResult = this.judgeOutcome(attackType, this.enemyAttackType.toString())
        
        if(attackResult === 'dogfall'){
            // 再来一局
            this.resetGame()
        }else {
            attackResult === 'win'? (this.hintLabel.string = '玩家胜利'):(this.hintLabel.string = '玩家失败')
            
        }
    }

    // 重新进行游戏
    resetGame(){
        director.loadScene('GuessingFinger')
    }

   
}


